<template>
  <n-config-provider :locale="locales[$i18n.locale]['lang']" :date-locale="locales[$i18n.locale]['date']">
    <n-message-provider>
      <div id="root">
        <div class="container">
          <header
            class="d-flex flex-wrap align-items-center justify-content-center justify-content-md-between py-3 mb-4 border-bottom">
            <a class="d-flex align-items-center col-md-3 mb-2 mb-md-0 text-dark text-decoration-none" href="/">
              <img alt="Logo" height="42" src="./assets/Logo.png" width="42" />
              &nbsp; LumbaShark
            </a>

            <ul class="nav col-12 col-md-auto mb-2 justify-content-center mb-md-0">
              <li>
                <router-link :class="getNavbarLinkClass('introduce')" :to="{ name: 'introduce' }">{{
                  $t("common.navigator.introduce")
                }}</router-link>
              </li>
              <li>
                <router-link :class="getNavbarLinkClass('faqs')" :to="{ name: 'faqs' }">{{
                  $t("common.navigator.faqs")
                }}</router-link>
              </li>
            </ul>

            <div class="col-md-3 text-end">
              <div class="d-inline-block" v-if="!cookies.isKey('access_token')">
                <router-link :to="{ name: 'user.sign', query: { mode: 'login' } }" class="btn btn-primary me-2">
                  {{
                    $t("common.actions.login")
                  }}</router-link>
              </div>
              <div class="d-inline-block" v-else>
                <div class="dropdown">
                  <a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button"
                    data-bs-toggle="dropdown" aria-expanded="false">
                    {{ store.account.accountProfile.username }}
                  </a>
                  <ul class="dropdown-menu" aria-labelledby="navbarDarkDropdownMenuLink">
                    <li>
                      <router-link class="dropdown-item" :to="{ name: 'user.profile' }">{{$t("common.actions.profile")}}</router-link>
                    </li>
                    <li><button class="dropdown-item" @click="accountLogout">{{$t("common.actions.logout")}}</button></li>
                  </ul>
                </div>
              </div>
            </div>
          </header>
        </div>

        <div id="content">
          <div class="container" v-show="releasesRecord.display">
            <div class="card border-success">
              <div class="card-header">
                {{ $t("introduce.update.title") }}
              </div>
              <div class="card-body pb-0">
                <h5 class="card-title">{{ $t("introduce.update.changes-logs") }}</h5>
                <p class="card-text">
                <ul>
                  <li v-html="$t('introduce.update.changes')"></li>
                </ul>
                </p>
              </div>
              <div class="card-footer">
                <code>{{ releasesRecord.oldVersion }}</code>
                <span>&nbsp;{{ $t("introduce.update.upgrade") }}&nbsp;</span>
                <code>{{ releasesRecord.newVersion }}</code>
              </div>
            </div>
          </div>
          <router-view v-slot="{ Component }">
            <transition name="fade">
              <component :is="Component" />
            </transition>
          </router-view>
        </div>

        <div class="container" id="footer">
          <footer class="d-flex flex-wrap justify-content-between align-items-center py-3 my-4 border-top">
            <p class="col-md-4 mb-0 text-muted">SmartSheep Studio © 2022</p>

            <a class="col-md-4 d-flex align-items-center justify-content-center mb-3 mb-md-0 me-md-auto link-dark text-decoration-none"
              href="/">
              <img alt="Logo" height="42" src="./assets/Logo.png" width="42" />
            </a>
            <div class="nav col-md-2 justify-content-end">
              <select class="form-select" v-model="$i18n.locale">
                <option v-for="locale in $i18n.availableLocales" :key="`locale-${locale}`" :value="locale">
                  {{ locale }}
                </option>
              </select>
            </div>
          </footer>
        </div>
      </div>
    </n-message-provider>
    </n-config-provider>
</template>

<script setup>
import {
  NConfigProvider,
  NMessageProvider,
  zhCN,
  dateZhCN,
  enUS,
  dateEnUS,
} from "naive-ui";
import { useCookies } from "vue3-cookies";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "./stores/main";
import { onMounted, reactive, watch } from "vue";
import { useI18n } from "vue-i18n";

import * as packageInfo from "../package.json";

const { cookies } = useCookies();
const i18n = useI18n();
const store = useStore();
const route = useRoute();
const router = useRouter();
const locales = {
  "zh-CN": { lang: zhCN, date: dateZhCN },
  "en-US": { lang: enUS, date: dateEnUS },
};

function getNavbarLinkClass(name) {
  if (name === route.name) {
    return "nav-link px-2 link-secondary";
  }
  return "nav-link px-2 link-dark";
}

function accountLogout() {
  cookies.remove("access_token");
  router.go();
}

function initLocales() {
  if (cookies.isKey("locale")) {
    i18n.locale.value = cookies.get("locale");
  } else {
    if (i18n.availableLocales.includes(navigator.language)) {
      cookies.set("locale", navigator.language);
    } else {
      cookies.set("locale", "en-US");
    }
    i18n.locale.value = cookies.get("locale");
  }
}

const releasesRecord = reactive({
  display: false,
  oldVersion: "",
  newVersion: packageInfo.version,
});

function initReleasesRecord() {
  if (!cookies.isKey("using_version")) {
    console.warn("[RELEASE-RECORDS] A new user access the website!");
    cookies.set("using_version", packageInfo.version);
  } else if (cookies.get("using_version") !== packageInfo.version) {
    console.warn("[RELEASE-RECORDS] A new version of the website is released!");
    releasesRecord.oldVersion = cookies.get("using_version");
    cookies.set("using_version", packageInfo.version);
    releasesRecord.display = true;
  }
}

watch(i18n.locale, (value) => {
  cookies.set("locale", value);
});

onMounted(() => {
  initLocales();
  initReleasesRecord();
  if (!store.status.useable) {
    store
      .init()
      .then((status) => {
        if (!status) {
          console.error("[STORE] Failed to init store");
        }
      })
      .catch(() => {
        console.error("[STORE] Failed to init store(FATAL)");
      });
  }
});
</script>

<style>html,
body,
#app,
#root {
  width: 100vw;
  height: 100vh;
}

#content {
  min-height: 100%;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.25s ease-in-out;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}</style>
